

package com.ly.blog_common.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ly.blog_common.constant.Constant;

import java.util.Map;

/**
 * 查询参数 - 工具类 - 将param参数转成分页对象 - 加上防注入
 *
 *
 */
public class Query<T> {

    public IPage<T> getPage(Map<String, Object> params) {
        return this.getPage(params, null, false);
    }

    public IPage<T> getPage(Map<String, Object> params, String defaultOrderField, boolean isAsc) {
        //分页参数
        long curPage = 1;
        long limit = 10;

        if(params.get(Constant.PAGE) != null){
            curPage = Long.parseLong(String.valueOf(params.get(Constant.PAGE)));
        }
        if(params.get(Constant.LIMIT) != null){
            limit = Long.parseLong(String.valueOf(params.get(Constant.LIMIT)));
        }

        //分页对象
        Page<T> page = new Page<>(curPage, limit);

        //分页参数
        params.put(Constant.PAGE, page);

        //排序字段
        //防止SQL注入（因为sidx、order是通过拼接SQL实现排序的，会有SQL注入风险）
        Object orderObj = params.get(Constant.ORDER_FIELD);
        if(orderObj instanceof String[]) {
            //增加批量排序，需保证 传入字段和排序时数组类型
            String[] orderArr = (String[])orderObj;
            String[] orderArrOrder = (String[])params.get(Constant.ORDER);
            for(int i=0 ;i<orderArr.length;i++) {
                String orderField = SQLFilter.sqlInject(orderArr[i]);
                String order = (String) params.get(orderArrOrder[i]);
                if(Constant.ASC.equalsIgnoreCase(order)) {
                    page.addOrder(OrderItem.asc(orderField));
                }else {
                    page.addOrder(OrderItem.desc(orderField));
                }
            }
            return page;

        }else{
            String orderField = SQLFilter.sqlInject((String)orderObj);
            String order = (String) params.get(Constant.ORDER);

            //前端字段排序
            if(StringUtils.isNotBlank(orderField) && StringUtils.isNotBlank(order)){
                if(Constant.ASC.equalsIgnoreCase(order)) {
                    return  page.addOrder(OrderItem.asc(orderField));
                }else {
                    return page.addOrder(OrderItem.desc(orderField));
                }
            }
        }


        //没有排序字段，则不排序
        if(StringUtils.isBlank(defaultOrderField)){
            return page;
        }

        //默认排序
        if(isAsc) {
            page.addOrder(OrderItem.asc(defaultOrderField));
        }else {
            page.addOrder(OrderItem.desc(defaultOrderField));
        }



        return page;
    }
}
